package com.example.utils;


import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//自定义拦截器,判断用户是否登录，拦截后台访问
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //request.getSession().setAttribute("loginUser",123);
        //判断用户是否登陆
        Object loginUser = request.getSession().getAttribute("loginUser");

        if(null==loginUser){

            //response.sendRedirect("/login?error&url="+url);
            String url = String.valueOf(request.getRequestURL());
            response.sendRedirect("/login?url="+url);

            return false;
        }

        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
